package org.example.Server.service.examination.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.Server.mapper.examination.ExamMapper;
import org.example.Server.mapper.examination.TeachExamMapper;
import org.example.Server.mapper.paper.PaperPersonalMapper;
import org.example.Server.model.examination.*;
import org.example.Server.model.examination.qs.QSSubmitDTO;
import org.example.Server.model.examination.qs.QsAnsMax;
import org.example.Server.model.paper.PaperFormat;
import org.example.Server.model.paper.PaperHeader;
import org.example.Server.model.semester.SemStu;
import org.example.Server.service.examination.StuExamService;
import org.example.Server.utils.ResultAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static org.example.Server.utils.ExceptionEnum.SQL_ERROR;

@Slf4j
@Service
public class StuExamServiceImpl implements StuExamService {
    static final int RIGHT_ALL = 1;
    static final int RIGHT_HALF = 2;
    static final int QS_ERROR = 0;
    @Autowired
    ExamMapper examMapper;
    @Autowired
    PaperPersonalMapper paperPersonalMapper;
    @Autowired
    TeachExamMapper teachExamMapper;

    /**
     * 学生获取考试列表
     *
     * @param semId
     * @param status
     * @param userId
     * @return
     */
    @Override
    public ResultAPI getStuExamList(Integer semId, Integer status, Integer userId) {
        List<ExamShow> examShowList = examMapper.getExamStuList(semId, status, userId);
        return ResultAPI.success(examShowList);
    }

    /**
     * 学生端获取答题详情
     *
     * @param examStu
     * @return
     */
    @Override
    public ResultAPI getExamStuDetail(ExamStuDTO examStu) {
        Integer stuExamId = examStu.getStu_exam_id();
        Integer paperId = examStu.getPaper_id();
        Integer semId = examStu.getSem_id();
        Integer stuId = examStu.getUser_id();
        ExamStuDetail examStuDetail = new ExamStuDetail();
        try {
            //获取试卷头
            PaperHeader paperHeader = paperPersonalMapper.getPaperHeaderById(paperId);
            examStuDetail.setPaperHeader(paperHeader);
            //获取学生信息
            SemStu student = teachExamMapper.getStuByStuExamId(stuExamId, semId);
            examStuDetail.setStudent(student);
            //获取试卷模块应得分以及学生得分
            List<ExamStuFormat> examStuFormat = teachExamMapper.getExamStuFormat(stuExamId, paperId);
            examStuDetail.setExamStuFormat(examStuFormat);
            //获取题目以及得分明细
            //再获得试卷题型-显示每一题内容（包括答案以及选项（选择题
            //获取题型map
            List<PaperFormat> qsFormatList = paperPersonalMapper.getPaperFormatById(paperId);
            //按照题型获取
            for (int i = 0; i < qsFormatList.size(); i++) {
                String qsType = qsFormatList.get(i).getQs_type();
                //分题型
                if (qsType.equals("qna")) {
                    //问答题
                    ExamQna qna = new ExamQna(qsFormatList.get(i));
                    List<ExamStuQna> qnas = examMapper.getStuQandA(paperId, stuExamId, stuId);
                    qna.setItems(qnas);

                    if (qnas != null && !qnas.isEmpty()) {
                        examStuDetail.getQsList().add(qna);
                    }
                } else {
                    //选择类的
                    ExamSel paperSelect = new ExamSel(qsFormatList.get(i));
                    List<ExamStuSel> qSelects = examMapper.getStuQSelect(paperId, qsType, stuExamId, stuId);
                    paperSelect.setItems(qSelects);
                    //需要展示答案ABCD:需要有两个for循环叠加
                    //这个强转我有点难绷
//                    for (int j = 0; j < qSelects.size(); j++) {
//                        ExamStuSel qSelect = qSelects.get(j);
//                        String stu_ans = "";
//                        String qs_ans = "";
//                        for (int k = 0; k < qSelect.getOptions().size(); k++) {
//                            Option option = qSelect.getOptions().get(k);
//                            if (option.getStu_choosed()) {
//                                stu_ans += (char) (k + 'A');
//                            }
//                            if (option.getIs_right()) {
//                                qs_ans += (char) (k + 'A');
//                            }
//                        }
//                        qSelect.setStu_ans(stu_ans);
//                        qSelect.setQsel_ans(qs_ans);
//                        log.info("标准答案：{}", qs_ans);
//                        log.info("选择题答案：{}", qSelects.get(j).getQsel_ans());
//                    }
                    if (!qSelects.isEmpty()) {
                        examStuDetail.getQsList().add(paperSelect);
                    }
                    log.info("答题详情{}", examStuDetail.getQsList());
                }

            }
            return ResultAPI.success(examStuDetail);
        } catch (Exception e) {
            log.error("获取答题详情失败", e);
            return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
        }
    }

    /**
     * 学生提交考试试卷
     *
     * @param examSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public ResultAPI stuSubmit(ExamSubmitDTO examSubmitDTO) {
//        ExamSetting paperRule = teachExamMapper.getPaperRule(examSubmitDTO.getExam_id());
        //判断一下有没有已经提交了
        Integer flag = examMapper.getExamStuExist(examSubmitDTO);
        if (flag != null) {
            return ResultAPI.error("该学生已提交！");
        }
        // 先判题
        List<QSSubmitDTO> questions = examSubmitDTO.getQuestions();
        // stu_qs_exam传入值
//        List<QsStuExam> qsStuExams = new ArrayList<>();
        double stuScore = 0d;
        // 学生
        for (QSSubmitDTO question : questions) {
//            QsStuExam qsStuExam = new QsStuExam();
            Integer qsId = question.getQs_id();
            question.setQs_id(question.getQs_id());
            if (!question.getQs_type().equals("qna")) {
                // 判断对不对并获得分数
                QsAnsMax qsAnsMax = examMapper.getSelQsAnsMax(examSubmitDTO, qsId);
                int qsRes = checkSelAnswer(question, qsAnsMax);
                switch (qsRes) {
                    case RIGHT_ALL:
                        question.set_getright(true);
                        question.setStu_score(qsAnsMax.getMax_score());
                        stuScore += qsAnsMax.getMax_score();
                        break;
                    case RIGHT_HALF:
                        question.set_getright(false);
                        question.setStu_score(qsAnsMax.getMax_score() / 2);
                        stuScore += qsAnsMax.getMax_score() / 2;
                        break;
                    case QS_ERROR:
                        question.set_getright(false);
                        question.setStu_score(0d);
                        break;
                    default:
                        question.set_getright(false);
                        question.setStu_score(0d);
                        break;
                }

            } else {
                //问答题还没有想好是老师手动还是ai
                // 获取问答题的正确答案列表
                QsAnsMax qsQnaAnsMax = examMapper.getQnaQsAnsMax(examSubmitDTO, qsId);
                double stu_score = new Random().nextInt((int) (qsQnaAnsMax.getMax_score() + 1));
                question.setStu_score(stu_score);
                stuScore += stu_score;
            }
//            qsStuExams.add(qsStuExam);
        }
        // 更新stu_Exam:包括学生考试分数
        examSubmitDTO.setGet_score(stuScore);
        examMapper.addStuExamSubmit(examSubmitDTO);
        // 更新stu_exam_qs
        examMapper.addStuExamQsSubmit(examSubmitDTO.getStu_exam_id(), questions);
        // 更新stu_qs_sel
        List<QSSubmitDTO> selList = questions.stream().filter(item -> !Objects.equals(item.getQs_type(), "qna")).toList();
        if (!selList.isEmpty()) {
            examMapper.addStuExamSelSubmit(selList);
        }
        // 更新stu_qs_qna
        List<QSSubmitDTO> qnaList = questions.stream().filter(item -> Objects.equals(item.getQs_type(), "qna")).toList();
        if (!qnaList.isEmpty()) {
            examMapper.addStuExamQnaSubmit(qnaList);
        }
        return ResultAPI.success(examSubmitDTO.getStu_exam_id());
    }

    public static int checkSelAnswer(QSSubmitDTO submitDTO, QsAnsMax ansMax) {
        List<Integer> submittedAnsIds = submitDTO.getAns_ids();
        List<Integer> rightAnsIds = ansMax.getRight_ans_ids();
        log.info("正确ids:{}", rightAnsIds);
        log.info("学生给的ids:{}", submittedAnsIds);
        int result = QS_ERROR;
        if (submittedAnsIds == null || submittedAnsIds.isEmpty() || rightAnsIds == null || rightAnsIds.isEmpty()) {
            return result;
        } else if (new HashSet<>(rightAnsIds).containsAll(submittedAnsIds)) {
            if (new HashSet<>(submittedAnsIds).containsAll(rightAnsIds)) {
                result = RIGHT_ALL;
            } else {
                result = RIGHT_HALF;
            }
        }
        return result;
    }
}
